// 文章的处理函数模块
const path = require('path')
const db = require('../db/index')
const scrapeData = require('../utils/cheerioArt')
const cheerioArtUrl = require('../utils/cheerioArtUrl')
const cheerioCover = require('../utils/cheerioCover')
const cheerioArtDetails = require('../utils/cheerioArtDetails')
const getPuppeteerImageData = require('../utils/pupLazyLoad')
const pupLazyLoadText = require('../utils/pupLazyLoadText')
const {login} = require("./user");


// 获取-发布文章的处理函数
exports.addArticle = (req, res) => {
    console.log(req.file)
    if (!req.file || req.file.fieldname !== 'cover_img') return res.cc('文章封面是必选参数！')

    // TODO：证明数据都是合法的，可以进行后续业务逻辑的处理
    // 处理文章的信息对象
    const articleInfo = {
        // 标题、内容、发布状态、所属分类的Id
        ...req.body,
        // 文章封面的存放路径
        cover_img: path.join('/uploads', req.file.filename),
        // 文章的发布时间
        pub_date: new Date(),
        // 文章作者的Id
        author_id: req.user.id,
    }

    const sql = `insert into ev_articles set ?`
    db.query(sql, articleInfo, (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows !== 1) return res.cc('发布新文章失败！')
        res.cc('发布文章成功！', 0)
    })
}


// cheerio 爬取文章-文字
// 获取文章的处理函数
exports.getArticle = (req, res) => {
    // console.log(typeof req.query.channel_id)
    const HOST = 'https://www.jianshu.com'
    let URL
    // console.log(req.query.channel_id)
    switch (req.query.channel_id) {

        case '0': // 恋爱
            URL = HOST + '/c/7ef399ce43b7';
            break;
        case '1': //星座
            URL = HOST + '/c/4616ebea646e';
            break;
        case '2':  // 恋人规则
            URL = HOST + '/c/4ca048982c8d';
            break;
        case '3': // MBTI性格
            URL = HOST + '/c/20d7c5db5048';
            break;
        case '4': // 小说
            URL = HOST + '/c/ef6c439535d3';
            break;
        default :
            URL = HOST + '/c/GQ5FAs';
    }
    // console.log(URL)

    Promise.all([scrapeData(URL, '.note-list .content .title'),
        scrapeData(URL, '.note-list .content .abstract'),
        scrapeData(URL, '.note-list .content .meta .nickname'),
        cheerioArtUrl(URL, '.note-list .content .title'),
        cheerioCover(URL, '.note-list .have-img .wrap-img img')
    ]).then(([scrapedData, artAbstract, artAutName, artUrl, cover]) => {
        // const sql = 'insert into test_article set ?'
        // db.query(sql, {
        //     art_id: 4,
        //     title: '22',
        //     channel_id: 1,
        //     con:'333',
        //     arr:['www','333']
        // }, (err, results) => {
        //     // 判断 SQL 语句是否执行成功
        //     if (err) return console.log(err)
        //     if (results.affectedRows !== 1) return console.log('失败')
        //     // 注册用户成功
        //
        // })
        res.send(
            scrapedData.map((i, index) => ({
                title: i,
                con: artAbstract[index],
                artUrl: `https://www.jianshu.com${artUrl[index]}`,
                art_id: artUrl[index].split(['/'])[2],
                aut_name: artAutName[index],
                cover: `${cover[index]}`,
                channel_id: req.query.channel_id
            }))
        )
    })
    //   const sql = `insert into test_article set ?`
    //       db.query(sql, {
    //           art_id:2,
    //           title:'222',
    //           channel_id:1,
    //       }, (err, results) => {
    //           if (err) return res.cc(err)
    //           if (results.length !== 1) return res.cc('获取文章分类数据失败！')
    //           res.cc(resObj,0)
    //       })


    // // 定义根据 ID 获取文章分类数据的 SQL 语句
    // const sql = `select * from ev_articles where art_id=?`
    // // 调用 db.query() 执行 SQL 语句
    // db.query(sql, 1, (err, results) => {
    //   if (err) return res.cc(err)
    //   if (results.length !== 1) return res.cc('获取文章分类数据失败！')
    //   res.send({
    //     status: 0,
    //     message: '获取文章分类数据成功！',
    //     data: results[0],
    //   })
    // })

}

// 获取文章的处理函数--文章详情页面
exports.getArticleDetails = (req, res) => {
    // console.log(req.params)
    const URL = 'https://www.jianshu.com/p/' + req.params.articleId
    // console.log(URL)
    Promise.all([scrapeData(URL, '._1RuRku'),
        cheerioArtDetails(URL, '._2rhmJa'),
        pupLazyLoadText(URL, '.s-dsoj time'),
        pupLazyLoadText(URL, '.FxYr8x ._1OhGeD'),
        getPuppeteerImageData(URL, '._13D2Eh')
    ]).then(([title, content, pubDate, aut_name, aut_photo]) => {
        res.send(
            {
                message: 0,
                data: {
                    aut_name: aut_name[0].text,
                    aut_photo: aut_photo[0].url,
                    content: content[0],
                    title: title[0],
                    pubDate: pubDate[0].text,
                    art_id: req.params.articleId,
                }
            }
        )
    })
}
